/* Filename: snder.c
 * Description: 消息队列，发送方
 * Last modified: humble 20200504 14:51
 */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>

#include "proto.h"

static void usage(void);

int main(int argc, char **argv)
{
    key_t key;
    int msgid;
    msg_t sbuf;

    if(argc != 1){
        fprintf(stderr, "argc !=1");
        usage();
        exit(1);
    }

    key = ftok(KEYPATH, KEYPROJ);
    if(key < 0){
        perror("ftok()");
        exit(1);
    }

    msgid = msgget(key, 0);
    if(msgid < 0){
        perror("msgget()");
        exit(1);
    }

    sbuf.mtype = 1;
    strcpy(sbuf.name, "Alan");
    sbuf.math = rand() % 100;
    sbuf.chinese = rand() % 100;
    if(msgsnd(msgid, &sbuf, sizeof(sbuf) - sizeof(long), 0) < 0){
        perror("msgsnd()");
        exit(1);
    }

    /* 不是发送方创建的，就不要在发送方销毁
    if(msgctl(msgid, IPC_RMID, NULL) < 0){
        perror("msgctl()");
        exit(1);
    }
    */

    return 0;
}

static void usage(void)
{
#define USAGE "Usage:\n\
  Helloworld\n"
    printf(USAGE);
}
